package com.sam.security;

import org.apache.struts2.config.ParentPackage;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.userdetails.UserDetails;

import com.sam.core.BaseAction;
import com.sam.core.Constants;
import com.sam.core.util.RequestUtils;
import com.sam.security.domain.User;

/**
 * spring security登录认证后续处理事件
 * 
 * @project EMan
 * @author Sam
 * @version
 * @date Feb 10, 2009 9:48:32 AM
 */
@ParentPackage("default")
public class AuthenticateAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	@Override
	public String execute() throws Exception {
		//通过spring security中是否存在认证对象来判断是否登录成功
		if ((getSession().getAttribute("SPRING_SECURITY_CONTEXT")) != null
				&& ((SecurityContext) (getSession()
						.getAttribute("SPRING_SECURITY_CONTEXT")))
						.getAuthentication() != null) {
			//将spring security中的UserDetails对象转换为系统的User对象
			UserDetails ud = (UserDetails) ((SecurityContext) (getSession()
					.getAttribute("SPRING_SECURITY_CONTEXT")))
					.getAuthentication().getPrincipal();
			User user = new User();
			user.setUsername(ud.getUsername());
			user.setPassword(ud.getPassword());
			//将当前用户和国际化资源对象放入session中
			getSession().setAttribute(Constants.USER_IN_SESSION, user);
			getSession().setAttribute(Constants.I18N_IN_SESSION, getTexts(RequestUtils.getConfig("struts.custom.i18n.resources")));
			sendJSON(true);
		} else {
			sendJSON(false);
		}
		return JSON;
	}
}
